/*
 * @Author: sunzhijun 
 * @Date: 2019-11-01 16:33:49 
 * @Last Modified by: sunzhijun
 * @Last Modified time: 2020-04-01 17:06:51
 */
import CommonAction from './common';
import newIncreasedRefs from '../components/NewAdd/functions';
import { chectFormAction, setFormAttrAndValue } from '../../../public/functions/checkFormAction';
import { saveValidate } from 'src/hrpub/common/utils/utils';

export default class newadd extends CommonAction {
    constructor(comp){
        super();
        this.comp = comp;
        this.dispatch = this.comp.props.dispatch;
    }

    // 上一步操作
    prevHandle = ()=>{
        // newIncreasedRefs.refs.prevHandleFn();
        this.cancelOccupy()
    }

    // 下一步操作 
    nextHandle = async ( selectData )=>{
        const { props } = this.comp;
        let { main, meta, form } = props;
        let { appConfig, pk_org, language} = main;
        let pk_psnjob = [];
        selectData && selectData.map((v,i)=>{
            pk_psnjob.push(v.data.values.pk_psnjob.value);
        });
        let psnJobs = pk_psnjob;
        let areaCode = 'dataBase,dataBefore,dataAfter';
        try {
            let res = await this.dispatch({
                type: 'main/nextHandleAction',
                payload: {
                    pageCode: appConfig.pagecode,
                    pk_psnjobs: psnJobs,
                    areaCode: areaCode,
                    appCode: appConfig.appcode,
                    pk_org: pk_org
                }
            });
            if( res.success ){
                let data = res.data;
                let extendParam = data.extendParam;
                let rows = data.resultData.dataBase_add.rows;
                // let rollBackFlag = data.rollBackFlag;
                let template = {
                    dataAfter_add: data.template.dataAfter_add,
                    dataBase_add: data.template.dataBase_add,
                    dataBefore_add: data.template.dataBefore_add,
                    formrelation: data.template.formrelation
                }
                meta.addMeta(template);
                // this.setDataBeforeFormKey(props)
                // let values = rows[0].values;
                // let contractnum = values.contractnum.value;
                // 获取可编辑的key
                let items = props.meta.getMeta()['dataAfter_add'].items;
                let len = items.length;
                let editColumn = [];
                for (let i=0;i < len; i++) {
                    if (items[i].visible === true && items[i].disabled === false) {
                        editColumn.push(items[i].attrcode)
                    }
                }
                await this.dispatch({
                    type: 'main/update',
                    payload: {
                        formVisible: true,
                        editColumn,
                        rollBackFlag: res.data.rollBackFlag,
                        rollBackFlagBillCode: res.data.rollBackFlagBillCode
                        // contractnum,
                        // rollBackFlag,
                        // extendParam
                    }
                })
                /*let newifprop = rows[0].values.newifprop;
                if (newifprop.value === true || newifprop.value === 'Y') {
                    newifprop.display = language['hrcm-000018'];
                    newifprop.value = 'Y';
                } else {
                    newifprop.display = language['hrcm-000019'];
                    newifprop.value = 'N';
                }*/
                form.setAllFormValue({'dataBase_add': {rows: rows}});
                form.setFormStatus('dataBase_add', 'edit');
                let attrMap = data.attrMap;
                let valueMap = data.valueMap;
                setFormAttrAndValue(attrMap, valueMap, props, 'dataBase_add', ['dataBase_add', 'dataAfter_add']);
            }
        }catch (err) {
            this.prevHandle();
            // this.toast({
            //     color: 'danger',
            //     content: err.message
            // })
            throw err
        }
    }

    // 保存
    doneHandle = ( )=>{
        const { props, action } = this.comp;
        let { main, form } = props;
        let { appConfig: { appcode, pagecode }, pk_org, step, editColumn, isCardForm, language } = main;
        if (!form.isCheckNow('dataBase_add')) {
            return false
        }
        saveValidate(props, 'dataBase_add', 'dataBase_add', ['dataBefore_add', 'dataAfter_add'] , 'extcard').then( async () => {
            let formDataRows = form.getAllFormValue('dataBase_add').rows
            let formData = {
                model: {
                    rows: formDataRows
                }
            }
            let paramObj = {
                step: step,
                pk_org: pk_org,
                appCode: appcode,
                modename: 'hrcm_ctrtmng',
                formData: formData,
                editColumn: editColumn,
            }
            let res = await this.dispatch({
                type: 'main/newAddSaveAction',
                payload: {
                    ...paramObj
                }
            })
            if( res.success ){
                let data = res.data;
                this.dispatch({
                    type: 'main/update',
                    payload: {
                        step: data.step,
                        isDone: true
                    }
                })
                let title = language['hrcm-000041'] /*国际化：确认继续*/; 
                if (data.step !== '99') {
                    this.addSaveAfterTips(data.msg, title)
                } else {
                    let savedData = data.savedData;
                    // if (props.returnListOrCard && props.returnListOrCard() == 'cardList') {
                    //     let pk_ctrtmng = savedData[savedData.length - 1]
                    //     props.initDataShow(pk_ctrtmng)
                    //     let allpks = cacheTools.get('allpks')
                    //     allpks.push(pk_ctrtmng)
                    //     cacheTools.set('allpks', allpks)
                    //     cardPagination.setCardPaginationId({id: pk_ctrtmng, status: 1})
                    // }
                    this.toast({
                        color: 'success',
                        content: language['hrcm-000045'] // 保存成功
                    })
                    await this.dispatch({
                        type: 'main/update',
                        payload: {
                            savedData: savedData,
                            step: '0',
                            pk_ctrtmng: savedData && savedData[0],
                            cardPaginationStatus: 2
                        }
                    })
                    await action.tableAct.getTableData();
                    if( isCardForm ){
                        action.cardAct.getFormData();
                    }
                    this.onClose();
                    // if (props.refreshTableList) {
                    //     props.refreshTableList()
                    // }
                    // if (props.setIsInterrupt) {
                    //     props.setIsInterrupt(true)
                    // }
                }
            }
        })

    }

    // 点击生效之后的提示
    addSaveAfterTips = (message, title)=> {
        const { props } = this.comp;
        let { main: { language }} = props;
        promptBox({
            color: 'warning',
            title: title, // 确认继续
            content: message,
            noFooter: false,
            noCancelBtn: false,
            beSureBtnName: language['hrcm-000034'], // 是
            cancelBtnName: language['hrcm-000035'], // 否
            beSureBtnClick: this.doneHandle,
            hasCloseBtn: false,
            cancelBtnClick: this.cancelBtnClick.bind(this, title)
        })
    }

    // 关闭新增弹窗
    onClose = ()=>{
        const { props: {main:{isDone}} } = this.comp;
        !isDone && this.cancelOccupy();
        this.dispatch({
            type: 'main/update',
            payload: {
                setModalVisible: false,
                isDone: false
            }
        })
    }

    // form编辑前事件
    handleEditBefore = (props, moduleId, key, value,data)=>{
        const { main } = props;
        let { pk_org } = main;
        let meta = props.meta.getMeta();
        if(key === 'pk_conttext' || key === 'newpk_conttext'){
            meta['dataAfter_add'].items.find(item => item.attrcode === key).queryCondition = function () {
                return {
                    "pk_org": pk_org,
                    "GridRefActionExt": "nccloud.web.hrcm.make.sqlbuilder.ContModelGridSqlBuilder"
                }
            };
            props.meta.setMeta(meta);
        } else {
            let array = [moduleId, 'dataAfter_add', 'dataBefore_add'];
            for (let index = 0; index < array.length; index++) {
                const formid = array[index];
                let formItem = meta[formid].items.find(item => item.attrcode === key && item.itemtype === 'refer')
                if (!!formItem) {
                    formItem.queryCondition = function () {
                        return {
                            "pk_org": pk_org
                        }
                    };
                }
            }
            props.meta.setMeta(meta);
        }
        return true;
    }

    // form 编辑后事件
    onAfterEvent = (props, moduleId, key, value, oldValue)=>{
        const { action } = this.comp;
        action.cardAct.checkoutCardData(key , 'dataBase_add', props, ['dataBase_add', 'dataAfter_add']);
    }

      //取消下一步人员数据被占用
      async cancelOccupy(){
        const { props } = this.comp;
        let {main:{pk_org, rollBackFlag, rollBackFlagBillCode}} = props;
        let formCardId = 'dataBase_add';
        if( rollBackFlag || rollBackFlagBillCode){
            let occupyData = props.form.getAllFormValue(formCardId);
            let occupyValues = occupyData.rows[0].values;
            let billCode = occupyData && occupyValues.bill_code.value;
            let res = await this.dispatch({
                type: 'main/rollBackAction',
                payload: {
                    codeList: [], // 只有签订申请有合同编号回滚
                    pk_org: pk_org,
                    billCode: rollBackFlagBillCode ? billCode: '',
                    rollBackFlagBillCode: rollBackFlagBillCode,
                    rollBackFlag: rollBackFlag
                }
            })

            if (res.success) {
                /*清空表单所有数据*/
                props.form.EmptyAllFormValue(formCardId);
            }
        }
    }
 }